package nio.socket.block;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class ThreadPoolServer {
    private static final ThreadPoolExecutor threadPoll;
    private static int tCount=1;
    static {
        threadPoll = new ThreadPoolExecutor(2, 4, 3, TimeUnit.SECONDS, new LinkedBlockingQueue<>(4), (r)-> {
            Thread thread = new Thread(r,"server-thread-" + tCount);
            tCount++;
            return thread;
        });
    }

    public static void start(int port) {
        try {
            ServerSocket ss = new ServerSocket(port);
            System.out.println("启动服务器....");
            while (!Thread.currentThread().isInterrupted()) {
                Socket client = ss.accept();
                threadPoll.execute(new TimeServerHandler (client));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
